package chapter5.lessons.udpDemo02;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * @Project ：learn_java
 * @File ：ReceiveMessage.java
 * @IDE ：IntelliJ IDEA
 * @Author ：自由如风间
 * @Date ：2025/3/12 20:45
 * @Description ：For study.
 */

public class ReceiveMessage {
    public static void main(String[] args) throws IOException {

        // pt:port
        int pt = 10086;

        DatagramSocket ds = new DatagramSocket(pt);

        long startTime = System.currentTimeMillis();

        while (true) {
            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - startTime;
            if (elapsedTime >= 60000) {
                System.out.println("已过去 60 秒，程序退出。");
                System.exit(0);
            }

            byte[] bytes = new byte[1024];
            DatagramPacket dp = new DatagramPacket(bytes, bytes.length);

            ds.receive(dp);

            // 解析数据
            byte[] data = dp.getData();
            int len = dp.getLength();
            // InetAddress address = dp.getAddress();
            // int port = dp.getPort();
            String ip = dp.getAddress().getHostAddress();
            String name = dp.getAddress().getHostName();

            System.out.println(
                    "ip为：" + ip + "，主机号为：" + name +
                    "发送的数据是：" + new String(data, 0, len));

            // System.out.println(
            //         """
            //             ip为：%s，主机号为：%s
            //             发送的数据是：%s
            //         """.formatted(ip, name, new String(data, 0, len))
            // );

            // System.out.printf("""
            //             ip为：%s，主机号为：%s
            //             发送的数据是：%s
            //         %n""", ip, name, new String(data, 0, len));
        }

        // 解放资源
        // ds.close();
    }
}
